package algotithm.leetcode.string.test3;

/**
 * @author zhouyanxiang
 * @Date 2021-02-2021/2/5-14:05
 * @Title 3. 无重复字符的最长子串
 * @URL https://leetcode-cn.com/problems/longest-substring-without-repeating-characters/
 */
public class Solution {

    public static void main(String[] args) {
        String s = "pwwkew";
        Solution solution = new Solution();
        int length = solution.lengthOfLongestSubstring(s);
        System.out.println(length);
    }


    /*public int lengthOfLongestSubstring(String s) {
        if (s.length() < 2) {
            return s.length();
        }
        char[] c = s.toCharArray();
        int[] cnt = new int[128];
        int res = 1;
        for (int i = 0, j = 0; j < s.length(); j++) {
            cnt[c[j]]++;
            if (cnt[c[j]] == 2) {
                while (cnt[c[j]] == 2) {
                    cnt[c[i]]--;
                    i++;
                }
            }
            res = Math.max(res, j - i + 1);
        }
        return res;
    }*/

    public int lengthOfLongestSubstring(String s) {
        int len = s.length();
        if (len < 2) {
            return len;
        }
        int[] cnt = new int[128];
        char[] c = s.toCharArray();
        for (int i = 0 ; i < cnt.length ;i++) {
            cnt[i] = -1;
        }
        int l = 0;
        int res = 1;
        for (int r = 0; r < len; r++) {
            if (cnt[c[r]] != -1) {
                l = Math.max(l,cnt[c[r]] + 1);
            }
            cnt[c[r]] = r;
            res = Math.max(res, r - l + 1);
        }
        return res;
    }
}
